clear all
set more off
set mat 11000

set seed 913





capture program quan drop
program quan, eclass
	version 10.0
	syntax varlist(max=1) [, end1(varname) end2(varname) instr(varlist) prone(varlist) tau(integer 50) ] 
	tempname temp cutoff below prb temp2 prb2 temp3 tempa belowa cutoffa temp4 temp5 temp4a temp5a temp6 resid moment temp4_t tmp temp3_t 
	local tau2=`tau'
	local tau=`tau'/100
	local low1=9999999
	local high1=-9999999	
	local low2=9999999
	local high2=-9999999	

	local vvv=0
	foreach var of varlist `instr' {
		local vvv=`vvv'+1
	}
	matrix A=J(`vvv',`vvv',.)
	matrix Gamma=J(`vvv',1,.)

		
	tempname pdf cdf moment1 moment2 www temp5 temp3 temp5_t temp3_t moment2_t chi

	foreach var of varlist `prone' {
		tempname `var'_t
	}

	**initial estimate
	local fff=1
	local num=-1500
	while `num'<=2000 {
	local num2=-1000
	qui while `num2'<=2500 {
	
		local vvv=1
		gen `temp'=`varlist'-`num'*`end1'-`num2'*`end2'
		capture qreg `temp' `instr' `prone' , quan(`tau2') wls(8)
		if (_rc==0) {
		matrix T=e(V)
		matrix A=T[1..2,1..2]
		
	
		foreach var of varlist `instr' {
			matrix Gamma[`vvv',1]=_b[`var']
			local vvv=`vvv'+1
		}
		matrix W=Gamma'*syminv(A)*Gamma

		local rrr2=W[1,1]
		

		if (`fff'==1) {
			scalar residual1=`rrr2'				
			local beta1a=`num'
			local beta2a=`num2'
			local fff=2
		}
		else {

			if (`rrr2'<residual1) {
				local beta1a=`num'
				local beta2a=`num2'
				scalar residual1=`rrr2'

			}
		}


		if (`rrr2'<=5.991) {
			if (`num'<`low1') {
				local low1=`num'
			}
			if (`num'>`high1') {
				local high1=`num'
			}
			if (`num2'<`low2') {
				local low2=`num2'
			}
			if (`num2'>`high2') {
				local high2=`num2'
			}
		}
		}
		capture drop `temp'
		local num2=`num2'+1
	
	}

	local num=`num'+1
	}


	ereturn scalar low1=`low1'
	ereturn scalar high1=`high1'
	ereturn scalar low2=`low2'
	ereturn scalar high2=`high2'
	ereturn scalar b2=`beta2a'
	ereturn scalar b1=`beta1a'

	
end
